/**
 * <p>Title: ServiceZMCMF2.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张小飞
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-5 下午04:52:30  张小飞  Create
 *</pre>
 */
package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cm.Depot;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCMImportMaterial;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBase;
import com.baosight.sczx.zm.cm.domain.ZMCMReceiveGoodsInfo;
import com.baosight.sczx.zm.cm.domain.ZMCMStockPlanDetail;

/**
 * <p>Title: ServiceZMCMF2.java</p>
 * <p>Description: 到货登记管理-采购计划</p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张小飞
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-5 下午04:52:30  张小飞  Create
 *</pre>
 */
public class ServiceZMCMF2 extends ServiceEPBase {

	/**
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMF2</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:37:15 张小飞
	 * </p>
	 *
	*/
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo = this.query(inInfo);
		//inInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.units"));
		return inInfo;
	}

	/**
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMF2</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:37:15 张小飞
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public EiInfo query(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		StaticTools.setQueryParameters(inInfo, "fdPlanStatus", "全部到货", true);
		StaticTools.setQueryParameters(inInfo, "fdStatus", "0", true);
		StaticTools.setQueryParameters(inInfo, "isAll", "no", true);
		String typeCode = "(t1.FD_MATERIAL_CODE like '' OR t1.FD_MATERIAL_CODE is null";
		EiInfo outInfo = new EiInfo();
		Map inMap = new HashMap();
		String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
		String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
		if(isUseTypeManagement.equals("1"))
		{
			inMap.put("fdCheckinPeopleId", UserSession.getUserId());
			List _list = dao.query(sqlmap, inMap);
			List queryList = Utils.generateValidateData(_list);
			
			for(int j=0; j<queryList.size(); j++)
			{
				typeCode += " OR t1.FD_MATERIAL_CODE like '" + queryList.get(j).toString() + "%'";
			}
			typeCode += ")";
		}
		else
		{
			sqlmap = "ZMCMMaterialType.type";
			List queryList = dao.query(sqlmap, inMap);
			
			for(int i=0; i<queryList.size(); i++)
			{
				Map _map = (Map)queryList.get(i);
				typeCode += " OR t1.FD_MATERIAL_CODE like '" + _map.get("fdTypeCode").toString() + "%'";
			}
			typeCode += ")";
		}
		
		StaticTools.setQueryParameters(inInfo, "fdMaterialCodeStr", typeCode, true);
		outInfo.addBlock(Utils.generateOutBlock("result", new ZMCMStockPlanDetail(), inInfo, "ZMCMStockPlanDetail.queryInArrivalRegister", false));
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.units"));
		EiInfo tmpInfo = querySendGoodsNoteCode(outInfo);
		outInfo.set("fdSendGoodsNoteCode", tmpInfo.get("fdSendGoodsNoteCode"));
		return outInfo;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo queryReceiveGoods(EiInfo inInfo)
	{
		EiInfo outInfo = new EiInfo();
		
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		String typeCode = "";
		Map inMap = new HashMap();
		String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
		String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
		if(isUseTypeManagement.equals("1"))
		{
			inMap.put("fdImportPeopleId", UserSession.getUserId());
			List _list = dao.query(sqlmap, inMap);
			List queryList = Utils.generateValidateData(_list);
			typeCode = "(t1.FD_MATERIAL_CODE like ''";
			for(int j=0; j<queryList.size(); j++)
			{
				typeCode += " OR t1.FD_MATERIAL_CODE like '" + queryList.get(j).toString() + "%'";
			}
			typeCode += ")";
		}
		else
		{
			sqlmap = "ZMCMMaterialType.type";
			List queryList = dao.query(sqlmap, inMap);
			
			typeCode = "(t1.FD_MATERIAL_CODE like ''";
			for(int i=0; i<queryList.size(); i++)
			{
				Map _map = (Map)queryList.get(i);
				typeCode += " OR t1.FD_MATERIAL_CODE like '" + _map.get("fdTypeCode").toString() + "%'";
			}
			typeCode += ")";
		}

		StaticTools.setQueryParameters(inInfo, "fdMaterialCodeStr", typeCode, true);
		outInfo.addBlock(Utils.generateOutBlock("result", new ZMCMReceiveGoodsInfo(), inInfo, "ZMCMReceiveGoodsInfo.queryHasCodeNotImportMaterial", false));
		
		outInfo.set("fdNoteCode", "");
		outInfo.set("depotName", Depot.getDepots().get(0).getFdDepotName());//库房名称默认填入库房管理中建立的一级库房
		outInfo.set("userId", UserSession.getUserId());//用户Id默认填入库确认人
		outInfo.set("userName", UserSession.getInSessionProperty("UserCname"));//用户Name默认填入库确认人
		outInfo.addBlock(generateImportType());
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.units"));
		
		return queryNoteCode(outInfo);
	}
	
	/**
	 * <p>Function: insert</p>
	 * <p>Description: 办理入库</p>
	 * <p>return value: ServiceZMCMF2</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-11-30下午02:04:46 wangkun
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public EiInfo insert(EiInfo inInfo) 
	{
		boolean isRepeat = validate(inInfo, "ZMCMImportMaterial.validate", new HashMap<String, String>());
		
		if(isRepeat) {
			inInfo.setStatus(-1);
			inInfo.setMsg("入库单号重复，请重新输入入库单号！");
			return inInfo;
		}
		else 
		{
			LinkedList _link = new LinkedList();
			String fdNoteCode = inInfo.getBlock("baseBlock").getCellStr(0, "fdNoteCode");
			
			Map _map = new HashMap();
			//办理入库
			String imKey = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL");
			String fdImportType = inInfo.getBlock("baseBlock").getCellStr(0, "fdImportType");
			_map.put("fdKeyId", imKey);//主键
			_map.put("fdDepotCode", Depot.getDepots().get(0).getFdDepotCode());
			_map.put("fdDepotName", Depot.getDepots().get(0).getFdDepotName());
			_map.put("fdNoteCode", fdNoteCode);//主键
			_map.put("fdYear", MaterialBase.getAccountDate(inInfo.getBlock("baseBlock").getCellStr(0, "fdNoteDate"))[0]);
			_map.put("fdMonth", MaterialBase.getAccountDate(inInfo.getBlock("baseBlock").getCellStr(0, "fdNoteDate"))[1]);
			_map.put("fdResourceNoteCode", "");
			_map.put("fdImportType", fdImportType);
			_map.put("fdStatus", "");
			_map.put("fdNoteDate", inInfo.getBlock("baseBlock").getCellStr(0, "fdNoteDate"));
			_map.put("fdEditor", UserSession.getUserId());
			_map.put("fdRemark", "");
			
			dao.insert("ZMCMImportMaterial.insert", _map);
			
			for(int i=0; i<inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++)
			{
				String fdKeyId = inInfo.getBlock("result").getCellStr(i, "fdKeyId");//到货登记明细主键
				String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
				String invoiceSum = inInfo.getBlock("result").getCellStr(i, "fdInvoiceSum") == null ? "0.0" : inInfo.getBlock("result").getCellStr(0, "fdInvoiceSum");
				
				double fdInvoiceSum = Double.parseDouble(invoiceSum);
				double fdActualNumber = Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdActualNum"));
				double fdPrice = Double.parseDouble(inInfo.getBlock("result").getCellStr(i, "fdPrice"));
				double fdSum = fdPrice*fdActualNumber;
				
				Map map2 = new HashMap();
				map2.put("fdMaterialId", fdMaterialId);
				List<ZMCMMaterialBase> result2 = dao.query("ZMCMMaterialBase.query", map2);
				
				String fdYear = StaticTools.getYear();
				String fdMonth = StaticTools.getStringMonth();
				List month_list = dao.query("ZMCMMaterialBase.queryYearMonth", new HashMap());
				
				if(month_list.size() > 0)
				{
					fdYear = ((Map)month_list.get(0)).get("fdYear").toString();
					fdMonth = ((Map)month_list.get(0)).get("fdMonth").toString();
				}
				
				//如无该物资信息则进行新增操作
				if(result2.size() == 0)
				{
					Map inMap = new HashMap();
					inMap.put("fdKeyId", TablePk.getInstance().getNextValue("T_CM_MATERIALBASE"));
					inMap.put("fdDepotCode", Depot.getDepots().get(0).getFdDepotCode());
					inMap.put("fdDepotName", Depot.getDepots().get(0).getFdDepotName());
					inMap.put("fdYear", fdYear);
					inMap.put("fdMonth", fdMonth.toString());
					inMap.put("fdBusinessType", "正常入库");
					inMap.put("fdNum", fdActualNumber);
					inMap.put("fdSum", fdSum);
					inMap.put("fdLastImportDate", StaticTools.getDate());
					inMap.put("fdMaterialId", fdMaterialId);
					inMap.put("fdMaterialCode", inInfo.getBlock("result").getCellStr(i, "fdMaterialCode"));
					inMap.put("fdMaterialInnerCode", inInfo.getBlock("result").getCellStr(i, "fdMaterialInnerCode"));
					inMap.put("fdMaterialName", inInfo.getBlock("result").getCellStr(i, "fdMaterialName"));
					inMap.put("fdMaterialType", inInfo.getBlock("result").getCellStr(i, "fdMaterialType"));
					inMap.put("fdSpecModel", inInfo.getBlock("result").getCellStr(i, "fdSpecModel"));
					inMap.put("fdNumber", inInfo.getBlock("result").getCellStr(i, "fdNumber"));
					inMap.put("fdQuality", inInfo.getBlock("result").getCellStr(i, "fdQuality"));
					inMap.put("fdMetric", inInfo.getBlock("result").getCellStr(i, "fdMetric"));
					inMap.put("fdPrice", fdPrice);
					
					if(fdInvoiceSum != Double.parseDouble("0.0"))
					{
						inMap.put("fdActualPrice", BigDecimal.valueOf(fdInvoiceSum / fdActualNumber));
						inMap.put("fdActualSum", fdInvoiceSum);
					}
					else
					{
						inMap.put("fdActualPrice", fdPrice);
						inMap.put("fdActualSum", BigDecimal.valueOf(fdSum));
					}
					
					if("一般入库".equals(fdImportType))
					{
						inMap.put("fdHasinvoiceNum", fdActualNumber);
						inMap.put("fdNoinvoiceNum", 0);
					}
					else if("估收入库".equals(fdImportType))
					{
						inMap.put("fdHasinvoiceNum", 0);
						inMap.put("fdNoinvoiceNum", fdActualNumber);
					}
					else
					{
						inMap.put("fdHasinvoiceNum", 0);
						inMap.put("fdNoinvoiceNum", 0);
					}
					
					dao.insert("ZMCMMaterialBase.insertStorage", inMap);
				
				}
				//更新库存中已存在物资信息
				else
				{
					Map inMap = new HashMap();
					double fdActualSum = result2.get(0).getFdActualSum();
					double fdNum = 	result2.get(0).getFdNum();
					
					//计算实际单价，填入当前库存中物资的实际单价字段
					if(fdInvoiceSum != Double.parseDouble("0.0"))
					{
						inMap.put("fdActualPrice", BigDecimal.valueOf((fdActualSum+fdInvoiceSum)/(fdNum + fdActualNumber)));
						inMap.put("fdActualSum", BigDecimal.valueOf(fdActualSum+fdInvoiceSum));
					}
					else
					{
						inMap.put("fdActualPrice", BigDecimal.valueOf((fdSum+fdActualSum)/(fdNum + fdActualNumber)));
						inMap.put("fdActualSum", BigDecimal.valueOf(fdSum+fdActualSum));
					}
					
					if("一般入库".equals(fdImportType))
					{
						inMap.put("fdHasinvoiceNum", BigDecimal.valueOf(result2.get(0).getFdHasinvoiceNum()==null?0.0:result2.get(0).getFdHasinvoiceNum()+fdActualNumber));
						inMap.put("fdNoinvoiceNum", result2.get(0).getFdNoinvoiceNum());				
					}
					else if("估收入库".equals(fdImportType))
					{
						inMap.put("fdHasinvoiceNum", result2.get(0).getFdHasinvoiceNum());
						inMap.put("fdNoinvoiceNum", BigDecimal.valueOf(result2.get(0).getFdNoinvoiceNum()+fdActualNumber));
					}
					else
					{
						inMap.put("fdHasinvoiceNum", result2.get(0).getFdHasinvoiceNum());
						inMap.put("fdNoinvoiceNum", result2.get(0).getFdNoinvoiceNum());
					}
					
					//更新库存中已存在物资的数量、单价、计划单价等信息
					inMap.put("fdMaterialId", fdMaterialId);
					inMap.put("fdNum", BigDecimal.valueOf(fdNum + fdActualNumber));
					inMap.put("fdSum", BigDecimal.valueOf((fdNum + fdActualNumber)*fdPrice));
					inMap.put("fdLastImportDate", StaticTools.getDate());
					dao.update("ZMCMMaterialBase.updateAfterStorage", inMap);
				}
				
				//处理入库明细中同一的合并
				if(_link.contains(fdMaterialId))
				{
					Map inMap = new HashMap();
					if(inInfo.getBlock("result").getCellStr(i, "fdInvoice") != null && !"".equals(inInfo.getBlock("result").getCellStr(i, "fdInvoice")))
					{
						inMap.put("fdInvoice", ";"+inInfo.getBlock("result").getCellStr(i, "fdInvoice"));
					}
					else
					{
						inMap.put("fdInvoice", "");
					}
					inMap.put("fdSum", BigDecimal.valueOf(fdSum));
					inMap.put("fdPlanNumber", inInfo.getBlock("result").getCellStr(i, "fdActualNum"));
					inMap.put("fdActualNumber", inInfo.getBlock("result").getCellStr(i, "fdActualNum"));
					inMap.put("fdInvoiceSum", inInfo.getBlock("result").getCellStr(i, "fdInvoiceSum"));
					inMap.put("fdImportmaterialId", imKey);
					inMap.put("fdMaterialId", fdMaterialId);
					
					dao.update("ZMCMImportmaterialDetail.updateBatchDetail", inMap);
				}
				else
				{
					Map inMap = new HashMap();
					inMap.put("fdKeyId", TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL_DETAIL"));
					inMap.put("fdImportmaterialId", imKey);
					inMap.put("fdProvideDepartment", inInfo.getBlock("result").getCellStr(i, "fdSupplyName"));
					inMap.put("fdMaterialSource", inInfo.getBlock("result").getCellStr(i, "fdMaterialSource"));
					inMap.put("fdInvoice", inInfo.getBlock("result").getCellStr(i, "fdInvoice"));
					inMap.put("fdMaterialId", fdMaterialId);
					inMap.put("fdMaterialCode", inInfo.getBlock("result").getCellStr(i, "fdMaterialCode"));
					inMap.put("fdMaterialName", inInfo.getBlock("result").getCellStr(i, "fdMaterialName"));
					inMap.put("fdSpecModel", inInfo.getBlock("result").getCellStr(i, "fdSpecModel"));
					inMap.put("fdNumber", inInfo.getBlock("result").getCellStr(i, "fdNumber"));
					inMap.put("fdQuality", inInfo.getBlock("result").getCellStr(i, "fdQuality"));
					inMap.put("fdStatus", inInfo.getBlock("result").getCellStr(i, "fdStatus"));
					inMap.put("fdReduceNumber",inInfo.getBlock("result").getCellStr(i, "fdReduceNumber"));
					inMap.put("fdMetric", inInfo.getBlock("result").getCellStr(i, "fdMetric"));
					inMap.put("fdSum", BigDecimal.valueOf(fdSum));
					inMap.put("fdPrice", fdPrice);
					inMap.put("fdPlanNumber", inInfo.getBlock("result").getCellStr(i, "fdActualNum"));
					inMap.put("fdActualNumber", inInfo.getBlock("result").getCellStr(i, "fdActualNum"));
					inMap.put("fdConfirmPeople", UserSession.getUserId());
					inMap.put("fdInvoiceSum", inInfo.getBlock("result").getCellStr(i, "fdInvoiceSum"));
					inMap.put("fdRemark", inInfo.getBlock("result").getCellStr(i, "fdRemark"));

					dao.insert("ZMCMImportmaterialDetail.insert", inMap);
					_link.add(fdMaterialId);
				}
				
				//将入库单据编号填入到货登记表中的入库单号字段
				Map inMap = new HashMap();
				inMap.put("fdKeyId", fdKeyId);
				inMap.put("fdImportnoteCode", fdNoteCode);
				dao.update("ZMCMReceiveGoodsInfo.updateAfterStorage", inMap);
			}
			
			return inInfo;
		}
	}
	
	/**
	 * 
	 * <p>Function: validate</p>
	 * <p>Description: 校验编号重复</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-18上午10:53:45 张小飞
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		
		String fdNoteCode = inInfo.getBlock("baseBlock").getCellStr(0, "fdNoteCode");
		
		params.put("fdNoteCode", fdNoteCode);
		
		List result = dao.query(sqlName, params);
		if(result != null && result.size() > 0) {
			inInfo.setStatus(-1);
			ZMCMImportMaterial im = (ZMCMImportMaterial)result.get(0);
			StringBuffer msg = new StringBuffer("提交失败，");
			if(im.getFdNoteCode() != null && im.getFdNoteCode().equals(fdNoteCode)) {
				msg.append(" 单据编号 ");
			}
			msg.append("重复！");
			inInfo.setMsg(msg.toString());
			return true;
		}
		return false;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private EiBlock generateImportType()
	{
		EiBlock block = new EiBlock("cmes.cm.queryImportType");
		EiColumn column = new EiColumn("value");
		column.setDescName("值");
		block.getBlockMeta().addMeta(column);
		
		column = new EiColumn("display");
		column.setDescName("名称");
		block.getBlockMeta().addMeta(column);
		
		Map inMap = new HashMap();
		inMap.put("value", "一般入库");
		inMap.put("display", "一般入库");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "估收入库");
		inMap.put("display", "估收入库");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "超前入库");
		inMap.put("display", "超前入库");
		block.addRow(inMap);
		
		return block;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo queryNoteCode(EiInfo inInfo)
	{
		List<Map> _list = new ArrayList<Map>();
		HashMap	params = new HashMap<String, String>();
		String startStr = "RK" + StaticTools.getDateDefault() + StaticTools.getTime().replaceAll(":", "");
		String defaultStr = startStr + "001";//定义格式
		_list = dao.query("ZMCMImportMaterial.querySerialNum", params);
		if(_list!=null && _list.size() > 0) {
			String str = _list.get(0).get("fdNoteCode").toString();
			defaultStr = convertStr(startStr, str);
		}
		
		inInfo.set("fdNoteCode", defaultStr);
		
		return inInfo;
	}
	
	private String convertStr(String startStr, String str)
	{
		String str1 = str.substring(16,19);//第二部分的流水号
		int nub = Integer.parseInt(str1); 
		str1 = Integer.toString(nub+1);
		if(str1.length() == 1){
			return startStr+"00"+str1;
		}else if (str1.length() == 2)
		{
			return startStr+"0"+str1;
		}else
		{
			return startStr+str1;
		}
	}
	
	public EiInfo querySendGoodsNoteCode(EiInfo inInfo)
	{
		String startStr = "SH" + StaticTools.getDateDefault() + StaticTools.getTime().replaceAll(":", "");
		
		EiInfo outInfo = new EiInfo();
		outInfo.set("fdSendGoodsNoteCode", startStr);
		
		return outInfo;
	}
}
